package rcs34.android.photopublishare;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.Buffer;
import java.util.Set;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import Utils.ImageUtils;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class ServiceUpload extends IntentService {
	private final String LOGTAG = getClass().getName();
	private File image = null;
	private int errorCount=0;

	public ServiceUpload() {
		super("Upload service");
	}

	@Override
	protected void onHandleIntent(Intent _intent) {
		errorCount=0;
		image = new File(_intent.getStringExtra(ImageUtils.EXIF_KEY_PATH));
		Set<String> extras = _intent.getExtras().keySet();
		String sselected = _intent
				.getStringExtra(ActivitySelectTarget.EXTRA_SELECTED_TARGETS);
		String[] selected = sselected.split(";");
		HardWorker worker = new HardWorker();
		worker.execute(selected);
	}

	private void HTTPUpload(URL _url, File _file) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(_url.toString());
		try {
			MultipartEntity multipartEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			multipartEntity.addPart("Image", new FileBody(_file));
			httpPost.setEntity(multipartEntity);

			HttpResponse response = httpclient.execute(httpPost);
			int code=response.getStatusLine().getStatusCode();
			Log.v(LOGTAG, "Response code is "
					+ code);
			if(code!=200){
				errorCount++;
			}
		} catch (ClientProtocolException e) {
			errorCount++;
			e.printStackTrace();
		} catch (IOException e) {
			errorCount++;
			e.printStackTrace();
		}
	}

	private void FTPUpload(URL _url, String _login, String _password, File _file) {
		FTPClient ftpClient = new FTPClient();

		try {
			ftpClient.connect(InetAddress.getByName(_url.getHost()));
			Log.v(LOGTAG,ftpClient.getReplyString());
            ftpClient.login(_login, _password);
            Log.v(LOGTAG,ftpClient.getReplyString());
			ftpClient.changeWorkingDirectory(_url.getPath());
			Log.v(LOGTAG,ftpClient.getReplyString());
			if (ftpClient.getReplyString().contains("250")) {
				ftpClient
						.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
				BufferedInputStream buffIn = null;
				buffIn = new BufferedInputStream(new FileInputStream(_file),1024);
				ftpClient.enterLocalPassiveMode();
				boolean result = ftpClient.storeFile(_file.getName(), buffIn);
				if(!result){
					errorCount++;
				}
				buffIn.close();
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (SocketException e) {
			errorCount++;
			e.printStackTrace();
		} catch (UnknownHostException e) {
			errorCount++;
			e.printStackTrace();
		} catch (IOException e) {
			errorCount++;
			e.printStackTrace();
		}

	}

	private class HardWorker extends AsyncTask<String, String, Integer> {
		@Override
		protected Integer doInBackground(String... _rowid) {
			DBHelper dbHelper = new DBHelper();
			for (int i = 0; i < _rowid.length; i++) {
				if (_rowid[i] != null && !_rowid[i].equals("")) {
					ContentValues values = dbHelper.getTarget(_rowid[i]);
					URL url;
					try {
						url = new URL(values.getAsString(DBHelper.COL_URL));
						publishProgress(url.toString());
						if (url.getProtocol().equals("http")) {
							HTTPUpload(url, image);
						} else if (url.getProtocol().equals("ftp")) {
							FTPUpload(url,
									values.getAsString(DBHelper.COL_LOGIN), 
									values.getAsString(DBHelper.COL_PASSWORD), 
									image);
						}
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return 0;
		}

		@Override
		protected void onProgressUpdate(String... _dummy) {
			createNotification(android.R.drawable.stat_sys_upload,0,"Uploading",getText(R.string.info_uploading_to)+" "+_dummy[0]);
		}

		@Override
		protected void onPostExecute(Integer _dummy) {
			String errString="No errors";
			int number=errorCount;
			if(errorCount>0){
				errString="Count of errors: "+errorCount;
			}
			createNotification(android.R.drawable.stat_sys_upload_done,number,"Uploading finished",errString);
			Toast.makeText(GApp.context, R.string.info_uploaded_everything,
					Toast.LENGTH_SHORT).show();
			
		}
		
		private void createNotification(int _img,int _number,String _title,String _info){
			NotificationManager notificationManager = (NotificationManager) 
					  getSystemService(NOTIFICATION_SERVICE); 
			Notification notification = new Notification(_img,
			  "Picture upload", System.currentTimeMillis());
	        notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.number=_number;
	        Intent notificationIntent = new Intent(GApp.context, ActivitySelectTarget.class); 
	        PendingIntent activityPendingIntent = PendingIntent.getActivity(GApp.context, 0, notificationIntent, 0);
	        notification.setLatestEventInfo(GApp.context,_title, _info, activityPendingIntent);
	        notificationManager.cancel(0);
	        notificationManager.notify(0, notification);
		}
	}
}
